package cn.stronglink.assetmanage.business.check.model;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.dao.AssetDao;
import cn.stronglink.assetmanage.dao.CheckDao;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.netrequest.business.check.CheckService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 待同步数据操作（只同步已经入库的数据，同步后的数据需要在本地删除）
 * Created by chencongcong on 2018/6/14.
 */

public class SyncAssetModel {
    private CheckService checkService;
    private onSyncCheckDataListener syncCheckDataListener;
    private Gson gson = new Gson();
    //需要同步的数据
    List<Check> syncCheckList = null;

    public onSyncCheckDataListener getSyncCheckDataListener() {
        return syncCheckDataListener;
    }

    public void setSyncCheckDataListener(onSyncCheckDataListener syncCheckDataListener) {
        this.syncCheckDataListener = syncCheckDataListener;
    }

    public SyncAssetModel() {
        checkService = new CheckService();
    }

    // 获取所有入库待同步的数据 status对应的状态还不确定，暂时定4为入库
    public List<Check> getDataByOrderNoDistince() {
        List<Check> checkList = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().queryBuilder().distinct()
                .orderDesc(CheckDao.Properties.Id_).
                        where(CheckDao.Properties.Status.eq(Constants.STATUS_FOUR)).list();
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).clear();
        if (checkList != null) {
            return checkList;
        }
        return null;
    }

    /**
     *  根据表单号获得该表单中已经入库的资产数据 暂时定4为入库
     *
     * @param orderNo
     * @return
     */
    public List<Asset> getDataByOrderNo(String orderNo) {
        //获取所有待入库的数据单列表
        List<Asset> assetList = DaoManager.getInstance(MyApplication.APP_CONTEXT).
                getDaoSession(MyApplication.APP_CONTEXT).getAssetDao().
                queryBuilder().where(AssetDao.Properties.OrderNo.eq(orderNo)).list();
        DaoManager.getInstance(MyApplication.APP_CONTEXT).getDaoSession(MyApplication.APP_CONTEXT).clear();
        if (assetList != null) {
            return assetList;
        }
        return null;
    }

    /**
     * 获取需要同步的数据串，传给接口
     *
     * @return
     */
    private String getSyncData() {
        syncCheckList = getDataByOrderNoDistince();
        if (syncCheckList != null && syncCheckList.size() > 0) {
            for (int i = 0; i < syncCheckList.size(); i++) {
                Check check = syncCheckList.get(i);
                check.setId(Long.valueOf(check.getId_()));
                List<Asset> assetList = getDataByOrderNo(check.getId_());
                if (assetList != null && assetList.size() > 0) {
                    for (int j = 0; j < assetList.size(); j++) {
                        Asset asset = assetList.get(j);
                        asset.setId(Long.valueOf(asset.getId_()));
                    }
                    check.setAssetList(assetList);
                }
            }
            String syncCheckData = gson.toJson(syncCheckList);
            return syncCheckData;
        }
        return null;
    }

    /**
     * 删除已经同步的资产数据
     */
    public void deteleSyncData() {
        if (syncCheckList != null && syncCheckList.size() > 0) {
            for (int i = 0; i < syncCheckList.size(); i++) {
                Check check = syncCheckList.get(i);
                List<Asset> assetList = getDataByOrderNo(check.getId_());
                if (assetList != null && assetList.size() > 0) {
                    for (int j = 0; j < assetList.size(); j++) {
                        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).
                                getAssetDao().delete(assetList.get(j));
                    }
                }
                DaoManager.
                        getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().delete(check);
            }
        }

        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).clear();
    }

    //数据同步需要一个单子一个单子来做，同一个线程中，一条单子成功，再进行下一条。
    public void syncCheckData() {
        String checkJson = getSyncData();
        try {
            // 调用接口，同步数据
            checkService.uploadCheckList(checkJson, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (syncCheckDataListener != null) {
                        syncCheckDataListener.onFailer(call, e);
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (syncCheckDataListener != null) {
                        syncCheckDataListener.onResponse(call, response);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过单号id获得check类
     * @param orderNo
     * @return
     */
    public Check getCheckByOrderNo(String orderNo) {
        Check check = DaoManager.
                getDaoSession(MyApplication.APP_CONTEXT).getCheckDao().queryBuilder().distinct()
                .orderDesc(CheckDao.Properties.Id_).
                        where(CheckDao.Properties.Id_.eq(orderNo)).
                        where(CheckDao.Properties.Status.eq(Constants.STATUS_FOUR)).list().get(0);
        DaoManager.getDaoSession(MyApplication.APP_CONTEXT).clear();
        if (check != null) {
            return check;
        }
        return null;
    }

    public interface onSyncCheckDataListener {
        void onFailer(Call call, IOException e);

        void onResponse(Call call, Response response);
    }

}
